package com.lonely.order.support.synchronizer.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lonely.order.domain.dto.api.GetPurchaseInfoReqDTO;
import com.lonely.order.domain.dto.api.GetPurchaseInfoResDTO;
import com.lonely.order.domain.entity.SysOrderPartMaterial;
import com.lonely.order.domain.entity.SysSheinOpenApiSecret;
import com.lonely.order.service.IMesApiService;
import com.lonely.order.service.IOrderPartMaterialService;
import com.lonely.order.threadlocals.OrderSynchronizedThreadLocal;
import com.lonely.purchase.domain.entity.SysMaterialPurchase;
import com.lonely.purchase.enums.MaterialPurchaseEnum;
import com.lonely.purchase.service.IMaterialPurchaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/7/31 15:30
 * @description: 同步订单采购单数据服务
 */
@Service
@Slf4j
public class SynchronizerOrderPurchaseService {

    @Autowired
    private IMaterialPurchaseService materialPurchaseService;

    @Autowired
    private IMesApiService mesApiService;

    @Autowired
    private IOrderPartMaterialService orderPartMaterialService;

    /**
     * 同步订单采购单
     */
    @Transactional(rollbackFor = Exception.class)
    public void synchronizerOrderPurchase(SysSheinOpenApiSecret openApiSecret, List<Long> orderIds) {
        // 有效的订单号集合
        List<Long> effectiveOrderIds = new ArrayList<>();
        if (CollUtil.isNotEmpty(orderIds)) {
            List<SysMaterialPurchase> existsOrderPurchases = materialPurchaseService.list(new LambdaQueryWrapper<SysMaterialPurchase>()
                    .in(SysMaterialPurchase::getProduceOrderId, orderIds));
            List<Long> existsOrderPurchaseIds = existsOrderPurchases.stream().map(SysMaterialPurchase::getProduceOrderId).distinct().collect(Collectors.toList());

            // 剔除已存在的订单号
            effectiveOrderIds = orderIds.stream().filter(x -> !existsOrderPurchaseIds.contains(x)).collect(Collectors.toList());
        }

        if (CollUtil.isEmpty(effectiveOrderIds)) {
            return;
        }

        // 因为该接口每次订单id最多50条，所以需要切割一下
        List<List<Long>> split = CollUtil.split(effectiveOrderIds, 50);
        for (List<Long> currentBatchOrderIds : split) {
            // 获取指定订单对应的采购信息
            GetPurchaseInfoReqDTO getPurchaseInfoReqDTO = new GetPurchaseInfoReqDTO();
            getPurchaseInfoReqDTO.setProduceOrderIdList(currentBatchOrderIds);
            List<GetPurchaseInfoResDTO> purchaseInfo = mesApiService.getPurchaseInfo(openApiSecret, getPurchaseInfoReqDTO);
            if (CollUtil.isEmpty(purchaseInfo)) {
                return;
            }

            // 获取指定订单号指定sku对应的物料单位映射
            List<String> materialSkus = purchaseInfo.stream().filter(x -> CollUtil.isNotEmpty(x.getPurchaseInfo()))
                    .flatMap(x -> x.getPurchaseInfo().stream())
                    .map(GetPurchaseInfoResDTO.PurchaseInfo::getMaterialSku)
                    .filter(StrUtil::isNotBlank)
                    .distinct()
                    .collect(Collectors.toList());
            Map<String, String> materialUnitMap = new HashMap<>();
            if (CollUtil.isNotEmpty(materialSkus)) {
                List<SysOrderPartMaterial> sysOrderPartMaterials = this.orderPartMaterialService.list(new LambdaQueryWrapper<SysOrderPartMaterial>()
                        .in(SysOrderPartMaterial::getMaterialSku, materialSkus)
                );
                materialUnitMap.putAll(sysOrderPartMaterials.stream().collect(Collectors.toMap(SysOrderPartMaterial::getMaterialSku, SysOrderPartMaterial::getUnit, (x, y) -> x)));
            }

            List<SysMaterialPurchase> sysMaterialPurchases = new ArrayList<>();
            purchaseInfo.stream().filter(x -> CollUtil.isNotEmpty(x.getPurchaseInfo())).forEach(x -> {
                for (GetPurchaseInfoResDTO.PurchaseInfo currentPurchaseInfo : x.getPurchaseInfo()) {
                    SysMaterialPurchase sysMaterialPurchase = new SysMaterialPurchase();
                    BeanUtils.copyProperties(currentPurchaseInfo, sysMaterialPurchase);
                    sysMaterialPurchase.setOrderId(null);
                    sysMaterialPurchase.setSourceGoodsMaterialId(null);
                    sysMaterialPurchase.setType(MaterialPurchaseEnum.PurchaseTypeEnum.SHEIN.getType());
                    sysMaterialPurchase.setProduceOrderId(Convert.toLong(x.getProduceOrderId()));
                    sysMaterialPurchase.setSupplierColorCode(currentPurchaseInfo.getSupplierColorNum());
                    sysMaterialPurchase.setFactoryId(openApiSecret.getFactoryId());
                    sysMaterialPurchase.setCustomerId(openApiSecret.getCustomerId());
                    // 设置单位
                    String unit = MapUtil.getStr(materialUnitMap, currentPurchaseInfo.getMaterialSku(), null);
                    sysMaterialPurchase.setUnit(unit);

                    sysMaterialPurchase.setStatus(MaterialPurchaseEnum.MaterialPurchaseStatusEnum.TO_BE_PURCHASED.getStatus());
                    sysMaterialPurchase.setCreateBy(OrderSynchronizedThreadLocal.getCreateBy());
                    sysMaterialPurchase.setUpdateBy(OrderSynchronizedThreadLocal.getCreateBy());
                    sysMaterialPurchases.add(sysMaterialPurchase);
                }
            });
            if (CollUtil.isNotEmpty(sysMaterialPurchases)) {
                materialPurchaseService.saveBatch(sysMaterialPurchases);
            }
        }
    }


}
